package com.example.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.course.dto.admin.*;
import com.example.course.dto.user.UserScoresListDto;
import com.example.course.mapper.*;
import com.example.course.pojo.*;
import com.example.course.service.ScoresService;
import com.example.course.utils.common.enums.Code;
import com.example.course.utils.common.result.PageResponseResult;
import com.example.course.utils.common.result.Result;
import com.example.course.utils.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 24354
* @description 针对表【scores】的数据库操作Service实现
* @createDate 2024-03-15 15:13:44
*/
@Service
@Slf4j
public class ScoresServiceImpl extends ServiceImpl<ScoresMapper, Scores>
    implements ScoresService{

    @Autowired
    private ScoresMapper scoresMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result getUserScores( Long semesterId) {
        //token校验
        Long userId = BaseContext.getCurrentId();
        User checkUser = userMapper.selectById(userId);
        //未登录
        if (userId==null||checkUser==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //查询列表
        List<Scores> scoresList = scoresMapper.selectList(Wrappers.<Scores>lambdaQuery()
                .eq(Scores::getScoresUserId, userId));
        //条件查询
        if (semesterId!=null) {
            List<Scores> list = scoresMapper.selectList(Wrappers.<Scores>lambdaQuery()
                    .eq(Scores::getScoresUserId, userId)
                    .eq(Scores::getSemesterId, semesterId));
            return Result.okResult(list);
        }
        return Result.okResult(scoresList);
    }

    @Override
    public Result saveScores(AdminScoresSaveDto dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //学号查询
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getStudentId, dto.getStudentNum()));
        Course course = courseMapper.selectById(dto.getCourseId());
        //课程类别查询
        Category category = categoryMapper.selectById(dto.getCategoryId());
        if (course==null||category==null||user==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        //重复校验
        List<Scores> checkScoresList = scoresMapper.selectList(Wrappers.<Scores>lambdaQuery()
                .eq(Scores::getScoresCourseId, dto.getCourseId())
                .eq(Scores::getSemesterId, dto.getSemesterId())
                .eq(Scores::getScoresUserId,user.getUserId()));
        //有重复的成绩单
        if (!CollectionUtils.isEmpty(checkScoresList)||checkScoresList.size()>0) {
            return Result.errorResult(Code.DATA_EXIST);
        }
        //构建实体
        Scores scores=new Scores();
        scores.setScoresUserId(user.getUserId());
        scores.setScoresCourseId(dto.getCourseId());
        scores.setScoresCourseCategoryId(dto.getCategoryId());
        scores.setScoresCourseName(course.getCourseName());
        scores.setScoresCourseNumber(course.getCourseNumber());
        scores.setScoresGrade(dto.getGrade());
        scores.setScoresCourseOrdinal(course.getCourseOrdinal());
        scores.setScoresCourseCategoryName(category.getCategoryName());
        scores.setScoresCourseNature(course.getCourseNature());
        scores.setScoresCrs(dto.getCrs());
        scores.setScoresHours(dto.getHours());
        scores.setScoresCourseStudy(course.getCourseStudy());
        scores.setScoresCourseMajor(course.getCourseMajor());
        scores.setScoresTime(dto.getTime());
        scores.setScoresGradePoints(dto.getGradePoints());
        scores.setScoresRebuild(dto.getRebuild());
        scores.setSemesterId(dto.getSemesterId());
        //添加
        int checkSave = scoresMapper.insert(scores);
        if (checkSave==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result removeScores(AdminScoresRemoveDto dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //数据存在校验
        Scores checkScores = scoresMapper.selectById(dto.getScoresId());
        if (checkScores==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        //删除
        int checkRemove = scoresMapper.deleteById(dto.getScoresId());
        if (checkRemove==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result updateGetScores(AdminScoresUpdateGetDto dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //查询修改
        Scores checkScores = scoresMapper.selectById(dto.getScoresId());
        if (checkScores==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        User checkUser = userMapper.selectById(checkScores.getScoresUserId());
        Map<String ,Object> map=new HashMap<>();
        map.put("studentNumber",checkUser.getStudentId());
        map.put("scores",checkScores);
        return Result.okResult(map);
    }

    @Override
    public Result updateScores(AdminScoresUpdateDto dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //查询该学号是否存在
        User checkUser = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getStudentId, dto.getStudentNum()));
        //查询修改成绩是否存在
        Scores checkScores = scoresMapper.selectById(dto.getScoresId());
        if (checkScores==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        if (checkUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        //构建
        Scores scores=new Scores();
        BeanUtils.copyProperties(checkScores,scores);
        //为空时用旧数据，不为空时用新数据
        if (dto.getStudentNum()!=null) {
            scores.setScoresUserId(checkUser.getUserId());
        }
        if (!dto.getScoresGrade().equals("")) {
            log.info("qwq");
            scores.setScoresGrade(dto.getScoresGrade());
        }
        if (!dto.getScoresCrs().equals("")) {
            scores.setScoresCrs(dto.getScoresCrs());
        }
        if (!dto.getScoresHours().equals("")) {
            scores.setScoresHours(dto.getScoresHours());
        }
        if (!dto.getScoresTime().equals("")) {
            scores.setScoresTime(dto.getScoresTime());
        }
        if (!dto.getScoresGradePoints().equals("")) {
            scores.setScoresGradePoints(dto.getScoresGradePoints());
        }
        if (!dto.getScoresRebuild().equals("")) {
            scores.setScoresRebuild(dto.getScoresRebuild());
        }
        if (dto.getSemesterId()!=null) {
            scores.setSemesterId(dto.getSemesterId());
        }
        //修改
        int checkUpdate = scoresMapper.updateById(scores);
        if (checkUpdate==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getAdminScores(AdminScoresListDto dto) {
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //页码重置
        dto.checkParam();
        //构建分页参数
        IPage page=new Page(dto.getPage(),dto.getSize());
        //获取lambda数据
        LambdaQueryWrapper<Scores> wrapper=new LambdaQueryWrapper<>();
        if (dto.getSemesterId()!=null) {
            wrapper.eq(Scores::getSemesterId,dto.getSemesterId());
        }
        wrapper.orderByDesc(Scores::getScoresId);
        //注入page分页组件
        page=page(page,wrapper);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

}




